package cn.sdhuijin.healthexam.activity;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Properties;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import cn.sdhuijin.healthexam.DatabaseHelper;
import cn.sdhuijin.healthexam.R;
import cn.sdhuijin.healthexam.bean.User;
import cn.sdhuijin.healthexam.control.AbstractControlActivity;
import cn.sdhuijin.healthexam.util.Constants;
import cn.sdhuijin.healthexam.util.DESPlus;
import cn.sdhuijin.healthexam.util.Util;

import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.config.Config;
import com.qiniu.auth.JSONObjectRet;
import com.qiniu.io.IO;
import com.qiniu.io.PutExtra;
import com.qiniu.io.PutPolicy;

/**
 * 系统登录
 * 
 * 修改完成
 * 
 * @author sunping
 */
public class LoginActivity extends AbstractControlActivity implements
		OnClickListener {

	public static final int PICK_PICTURE_RESUMABLE = 0;
	boolean uploading = false;

	// 在七牛绑定的对应bucket的域名. 默认是bucket.qiniudn.com
	public static String bucketName = "huijin";
	public static String domain = bucketName + ".qiniudn.com";
	public String uptoken = "";
	String SerialNumber = android.os.Build.SERIAL;
	int sn = Math.abs(SerialNumber.hashCode());
	String snCode = String.format("%012d", sn);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (!Util.allIsNotEmpty(getResignId()) || !isResign(getResignId())) {
			setContentView(R.layout.activity_resign);
			addTextView(R.id.resign_id, "Activation");
			addTextView(R.id.version_model, "Model");
			addTextView(R.id.version_release, "Version");
			addTextView(R.id.imei, "Imei");
			addTextView(R.id.mac_address, "MAC");
			addTextView(R.id.resign_date, "Date");
			EditText etSN = (EditText) findViewById(R.id.sn_id);
			EditText etModel = (EditText) findViewById(R.id.version_model);
			EditText etRelease = (EditText) findViewById(R.id.version_release);
			EditText etImei = (EditText) findViewById(R.id.imei);
			EditText etMac = (EditText) findViewById(R.id.mac_address);
			EditText etResignDate = (EditText) findViewById(R.id.resign_date);
			etSN.setText(snCode);
			etModel.setText(android.os.Build.MODEL); // 型号
			etRelease.setText(android.os.Build.VERSION.SDK + ","
					+ android.os.Build.VERSION.RELEASE); // 系统版本
			// Imei号
			TelephonyManager telephonyManager = (TelephonyManager) this
					.getSystemService(Context.TELEPHONY_SERVICE);
			etImei.setText(telephonyManager.getDeviceId());
			// MAC地址
			WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			etMac.setText(wifiInfo.getMacAddress());
			etResignDate.setText(Util.getCurrentDateTime());

			this.findViewById(R.id.resign_id).requestFocus();
			// Properties文件路径
			controlManager.setPropertiesPath(Constants.PROPERTIES_PATH
					+ "resign.txt");
			controlManager.toControl();
			this.setButtonListener(this, R.id.bt_resign, R.id.bt_cancel);
		} else {
			setContentView(R.layout.activity_login);
			// ExitApplication.getInstance().addActivity(this);

			// 用户名
			addTextView(R.id.login_username, "用户名");

			// Properties文件路径
			controlManager.setPropertiesPath(Constants.PROPERTIES_PATH
					+ "userName.txt");
			controlManager.toControl();

			if (Util.allIsNotEmpty(getControlValue(R.id.login_username))) {
				this.findViewById(R.id.login_password).requestFocus();
			}
			this.setButtonListener(this, R.id.bt_login);
			if (Util.isNetAvailable(this)) {
				Log.e("网络", "已连接");
				upload();
			} else {
				Log.e("检测网址", "尚未设置");
			}
		}
	}

	@Override
	public void onClick(View v) {
		int clickId = (Integer) v.getId();
		switch (clickId) {
		case R.id.bt_login:
			login();
			break;
		case R.id.bt_resign:
			resign();
			break;
		case R.id.bt_cancel:
			this.finish();
			break;
		}
	}

	private String getResignId() {
		Properties properties = null;
		File file = null;
		File dirFile = null;
		String id = null;
		try {
			properties = new Properties();
			dirFile = new File(Environment.getExternalStorageDirectory()
					+ "/health/");
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			file = new File(Environment.getExternalStorageDirectory()
					+ "/health/resign.txt");
			if (!file.exists()) {
				file.createNewFile();
			} else {
				properties.load(new FileInputStream(file));
				String resignId = properties.getProperty("Activation");
				if (Util.allIsNotEmpty(resignId)) {
					id = resignId;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return id;
	}

	private void login() {
		DatabaseHelper dbh = new DatabaseHelper(LoginActivity.this);
		String username = this.getControlValue(R.id.login_username);
		String password = this.getControlValue(R.id.login_password);
		if (Util.allIsNotEmpty(username, password)) {
			if (dbh.login(username, password)) {
				Log.i(this.getClass().getSimpleName(), "用户名:" + username
						+ "密码:" + password);
				Intent intent = new Intent();
				User user = new User();
				user.setName(username);
				User.setCurrentUser(user);
				if (username.equals("管理员")) {
					intent.setClass(LoginActivity.this,
							ManagementActivity.class);
				} else {
					intent.setClass(LoginActivity.this, IndexActivity.class);
				}
				controlManager.toProperties();
				startActivity(intent);
			} else if (username.equals("管理员") && password.equals("82393977")) {
				User user = new User();
				user.setName(username);
				User.setCurrentUser(user);
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this, ManagementActivity.class);
				controlManager.toProperties();
				startActivity(intent);
			} else {
				this.toastInformation(R.string.login_failed); // 提示登录失败
			}
		} else {
			this.toastInformation(R.string.login_input_not_null); // 提示不能为空
		}
	}

	private void resign() {
		String resignId = this.getControlValue(R.id.resign_id);
		if (Util.allIsNotEmpty(resignId)) {
			try {
				DESPlus des = new DESPlus("sdhuijin@8239*8239");// 自定义密钥
				String SerialNumber = android.os.Build.SERIAL;
				int sn = Math.abs(SerialNumber.hashCode());
				String snCode = String.format("%012d", sn);
				int tem = Math.abs(des.encrypt(snCode).hashCode() / 10000);
				System.out.println(tem);
				String str = String.format("%06d", tem);
				if (str.equals(resignId)) {
					controlManager.toProperties();
					this.toastInformation(R.string.resign_success);
					Intent intent = new Intent();
					intent.setClass(LoginActivity.this, LoginActivity.class);
					startActivity(intent);
					this.finish();
				} else {
					this.toastInformation(R.string.resign_failed);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			this.toastInformation(R.string.resign_input_not_null); // 提示不能为空
		}
	}

	private boolean isResign(String resignId) {
		Boolean flag = false;
		try {
			DESPlus des = new DESPlus("sdhuijin@8239*8239");// 自定义密钥
			int tem = Math.abs(des.encrypt(snCode).hashCode() / 10000);
			String str = String.format("%06d", tem);
			if (str.equals(resignId)) {
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	private void upload() {
		Config.ACCESS_KEY = "1z8wamQIDtpV2wWgzpUy1ztgyQmGp5CkMDX3YDF2";
		Config.SECRET_KEY = "q7_s-s6y2J_eIATmTUdmR7E065MwoAkZqwapb89S";
		Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
		// 请确保该bucket已经存在
		PutPolicy putPolicy = new PutPolicy(bucketName);
		try {
			uptoken = putPolicy.token(mac);
		} catch (AuthException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

		Uri uri = Uri.parse(Environment.getExternalStorageDirectory()
				+ "/health/resign.txt");
		if (uploading) {
			return;
		}
		uploading = true;

		String key = snCode + ".txt";
		PutExtra extra = new PutExtra();
		extra.params = new HashMap<String, String>();
		extra.params.put("x:a", "pad注册信息");
		IO.putFile(this, uptoken, key, uri, extra, new JSONObjectRet() {
			@Override
			public void onProcess(long current, long total) {
			}

			@Override
			public void onSuccess(JSONObject resp) {
				uploading = false;
			}

			@Override
			public void onFailure(Exception ex) {
				uploading = false;
			}
		});
	}
}
